package com.xadmin.sys.security;

import com.xadmin.sys.security.config.JWTConfig;
import com.xadmin.sys.rbac.mapper.UserMapper;
import com.xadmin.sys.rbac.pojo.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 获取当前用户的信息
 */
@RestController
@RequestMapping("/user")
public class GetLoginUserByToken {
    @Resource
    private UserMapper userMapper;

    @RequestMapping(value = "/getUserInfo",method = RequestMethod.GET)
    public User getUserInfo(){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String tokenHeader = request.getHeader(JWTConfig.tokenHeader);
            if (StringUtils.isNotBlank(tokenHeader)) {
                String token = tokenHeader.replace(JWTConfig.tokenPrefix, "");
                // 解析JWT
                Claims claims = Jwts.parser()
                        .setSigningKey(JWTConfig.secret)
                        .parseClaimsJws(token)
                        .getBody();
                // 获取用户名
                String username = claims.getSubject();
                String userId=claims.getId();
                // 根据id查询用户信息
                User user = new User();
                userMapper.getByName(username);
                return user;
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }
}
